package hu.issue.framework.web.controller;

import hu.issue.framework.web.Constants;
import hu.issue.framework.web.validation.ErrorMessages;
import hu.issue.framework.web.validation.RequestValidation;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AbstractFormController implements Controller {

	@Override
	public String handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		final String method = request.getMethod();
		if (method.equals("GET")) {
			return handleGet(request, response);
		}

		if (method.equals("POST")) {
			final ErrorMessages messages = new ErrorMessages();
			request.setAttribute(Constants.FORM_ERROR, messages);
			final RequestValidation validation = new RequestValidation(request, messages);
			buildValidation(validation);
			if (!validation.validate()) {
				return handleGet(request, response);
			}

			return handleSubmission(request, response, messages);
		}

		throw new ServletException("Illegal reques with " + method);
	}

	protected String getFormView() {
		return getControllerName() + "-form.jsp";
	}

	protected String getControllerName() {
		return getClass().getSimpleName().replaceAll("Controller", "").toLowerCase();
	}

	protected void buildModel(final HttpServletRequest request) throws Exception {

	}

	protected String handleGet(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		buildModel(request);
		return getFormView();

	}

	protected abstract String handleSubmission(HttpServletRequest request, HttpServletResponse response, ErrorMessages messages) throws Exception;

	protected void buildValidation(final RequestValidation validation) {

	}

}
